package com.personalblog.service.serviceImpl;

import com.personalblog.dto.BlogQuery;
import com.personalblog.handler.ApiNotFindException;
import com.personalblog.mapper.BlogMapper;
import com.personalblog.po.Blog;
import com.personalblog.po.Tag;
import com.personalblog.po.User;
import com.personalblog.service.BlogService;
import com.personalblog.utils.MarkdownUtils;
import com.personalblog.utils.MyBeanUtils;
import com.personalblog.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author jxau_scf
 * @date 2021/3/24 - 18:59
 */
@Service
public class BlogServiceImpl implements BlogService {

    private static final Logger logger = LoggerFactory.getLogger(BlogServiceImpl.class);

    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RedisTemplate redisTemplate;


    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED,rollbackFor = Exception.class)
    @Override
    public int insertBlog(Blog blog) {
        ValueOperations<String, Blog> operations = redisTemplate.opsForValue();
        int i = 0;
        if (blog.getBlogId() == null){
            blog.setBlogCreateTime(new Date());
            blog.setBlogUpdateTime(new Date());
            blog.setBlogViews(0);
            blogMapper.insertBlog(blog);
            Integer blogId = blog.getBlogId();
            //将tagList插入到中间表...
            List<Integer> tagIdList = convertToList(blog.getTagIds());
            i = blogMapper.insertBlogTag(blogId,tagIdList);
            if (i != 0){
                String key = "blog_" + blogId;
                Boolean hasKey = redisTemplate.hasKey(key);
                if (hasKey){
                    redisTemplate.delete(key);
                    logger.info("在redis中删除"+key+"的缓存");
                }
                Blog blog1 = blogMapper.findBlogById(blogId);
                if (blog1 != null){
                    operations.set(key, blog1);
                    logger.info("在redis中添加了" + key + "的缓存");
                }
            }
        }

//        else {
//            blog.setBlogUpdateTime(new Date());
//            blogMapper.insertBlog(blog);
//            Integer blogId = blog.getBlogId();
//            //删除t_blog_tag的tag
//            blogMapper.deleteBlogTagByBlogId(blogId);
//            //将tagList插入到中间表...
//            List<Integer> tagIdList = convertToList(blog.getTagIds());
//            i = blogMapper.insertBlogTag(blogId,tagIdList);
//            if (i<=0){
//                throw new ApiNotFindException("t_blog_Tag插入异常");
//            }
//        }
        return i;

    }
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED,rollbackFor = Exception.class)
    @Override
    public int deleteBlog(int blogId) {
        ValueOperations<String, Blog> operations = redisTemplate.opsForValue();
        blogMapper.deleteBlog(blogId);
        int i = blogMapper.deleteBlogTagByBlogId(blogId);
        if (i != 0){
            String key = "blog_" + blogId;
            Boolean hasKey = redisTemplate.hasKey(key);
            if (hasKey){
                redisTemplate.delete(key);
            }
        }
        return i;
    }

    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED,rollbackFor = Exception.class)
    @Override
    public int updateBlog(int blogId, Blog blog) {
        ValueOperations<String, Blog> operations = redisTemplate.opsForValue();
        //数据库中查出原数据，再将要修改的数据替换，最后插入到数据库中
        Blog b = blogMapper.findBlogById(blogId);
        if (b == null){
            throw new ApiNotFindException("该博客不存在");
        }
        BeanUtils.copyProperties(blog,b, MyBeanUtils.getNullPropertyNames(blog));
        b.setBlogUpdateTime(new Date());
        int result = blogMapper.updateBlog(b);
        if (result != 0){
            String key = "blog_" + blogId;
            Boolean hasKey = redisTemplate.hasKey(key);
            if (hasKey){
                redisTemplate.delete(key);
                logger.info("在redis中删除"+key+"的缓存");
            }
            Blog blog1 = blogMapper.findBlogById(blogId);
            if (blog1 != null){
                operations.set(key,blog1);
                logger.info("在redis中添加"+key+"的缓存");
            }
        }
        //删除t_blog_tag的tag
        blogMapper.deleteBlogTagByBlogId(blogId);
        //将tagList插入到中间表...
        List<Integer> tagIdList = convertToList(blog.getTagIds());
        int i = blogMapper.insertBlogTag(blogId,tagIdList);
        if (i<=0){
            throw new ApiNotFindException("t_blog_Tag插入异常");
        }

        return result;
    }

    @Override
    public Blog findBlogById(int blogId) {
//        ValueOperations<String,Blog> operations = redisTemplate.opsForValue();
//        String key = "blog_"+blogId;
//        Boolean hasKey = redisTemplate.hasKey(key);
//        if (hasKey){
//            Blog blog = operations.get(key);
//            logger.info("从缓存中读取" + key +"数据");
//            System.out.println("redis中的数据==============》" + blog);
//            return blog;
//        }else {
//            Blog blog = blogMapper.findBlogById(blogId);
//            System.out.println("数据库中查询出来的blog======>" + blog);
//            //写入缓存
//            operations.set(key,blog);
//            return blog;
//        }
        return blogMapper.findBlogById(blogId);
    }

    @Override
    public List<Blog> findBlogs() {
//        //设置一个key值
//        String key = "blogs";
//        //判断reids中是否有键为key的缓存
//        Boolean hasKey = redisUtil.hasKey(key);
//        if (hasKey){
//            List<Blog> blogs = (List<Blog>) redisUtil.get(key);
//            System.out.println("redis中的数据==============》" + blogs);
//            logger.info("从缓存中读取" + key +"数据");
//            return blogs;
//        }else {
//            List<Blog> blogs = blogMapper.findBlogs();
//            //写入缓存
//            redisUtil.set(key, blogs);
//            return blogs;
//        }

//        //设置一个key值
//        String key = "blogs";
//        ValueOperations<String,List<Blog>> operations = redisTemplate.opsForValue();
//        //判断reids中是否有键为key的缓存
//        Boolean hasKey = redisTemplate.hasKey(key);
//        if (hasKey){
//            List<Blog> blogs = operations.get(key);
//            System.out.println("redis中的数据==============》" + blogs);
//            logger.info("从缓存中读取" + key +"数据");
//            return blogs;
//        }else {
//            List<Blog> blogs = blogMapper.findBlogs();
//            //写入缓存
//            operations.set(key, blogs);
//            return blogs;
//        }


        return blogMapper.findBlogs();
    }

    @Override
    public List<Blog> findBlogsByTagId(int tagId) {
        return blogMapper.findBlogsByTagId(tagId);
    }

    @Override
    public List<Blog> findBlogsByTypeId(int typeId) {
        return blogMapper.findBlogsByTypeId(typeId);
    }

    @Override
    public List<Blog> findBlogsByBlogQuery(BlogQuery blogQuery) {
        return blogMapper.findBlogsByBlogQuery(blogQuery);
    }

    @Override
    public int findBlogCount() {
        return blogMapper.findBlogCount();
    }

    @Override
    public List<Blog> findBlogsOrderByUpdateTime(int pageSize) {
        return blogMapper.findBlogsOrderByUpdateTime(pageSize);
    }

    @Override
    public List<Blog> findBlogsByKeywordQuerySearch(String query) {
        return blogMapper.findBlogsByKeywordQuerySearch(query);
    }

    @Override
    public Blog getAndConvert(int blogId) {
        ValueOperations<String, Blog> operations = redisTemplate.opsForValue();
        String key = "blog_"+blogId;
        Boolean hasKey = redisTemplate.hasKey(key);
        Blog blog = null;
        if (hasKey){
             blog = operations.get(key);
            logger.info("在redis中读取" + key +"的数据");
        }else {
             blog = blogMapper.findBlogById(blogId);
             //写入缓存
             operations.set(key,blog);
            logger.info("在redis中添加" + key +"的缓存");
        }
        if (blog == null){
            throw new ApiNotFindException("该博客找不到");
        }
        Blog b = new Blog();
        BeanUtils.copyProperties(blog,b);
        String content = b.getBlogContent();
        b.setBlogContent(MarkdownUtils.markdownToHtmlExtensions(content));
        blogMapper.updateBlogViews(blogId);
        return b;
    }

    @Override
    public Map<String, List<Blog>> archiveBlog() {
        List<String> years = blogMapper.findGroupYear();
        HashMap<String, List<Blog>> map = new HashMap<>();
        for (String year : years){
            map.put(year,blogMapper.findBlogsByYear(year));
        }
        return map;
    }


    //    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED,rollbackFor = Exception.class)
//    @Override
//    public int insertBlogTag(Blog blog) {
//        this.insertBlog(blog);
//        Integer blogId = blog.getBlogId();
//        //将tagList插入到中间表...
//        List<Integer> tagIdList = convertToList(blog.getTagIds());
//        blogMapper.insertBlogTag(blogId,tagIdList);
//        return 0;
//    }
    private List<Integer> convertToList(String ids){
        List<Integer> list = new ArrayList<>();
        if (!"".equals(ids) && ids != null){
            String[] idarray = ids.split(",");
            for (int i=0;i<idarray.length;i++){
                list.add(new Integer(idarray[i]));
            }
        }
        return list;
    }

//    @Override
//    public Blog findBlogFetchType(int blogId) {
//        return blogMapper.findBlogFetchType(blogId);
//    }



}
